package top.broncho.gank.ui.activity

import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.PopupWindow
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_todo.*
import kotlinx.android.synthetic.main.toolbar.*
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import reactivecircus.flowbinding.android.view.clicks
import top.broncho.gank.R
import top.broncho.gank.adapter.TodoPopupAdapter
import top.broncho.gank.bean.TodoTypeBean
import top.broncho.gank.constant.Constant
import top.broncho.gank.databinding.ActivityTodoBinding
import top.broncho.gank.ui.fragment.TodoFragment
import top.broncho.gank.utils.DisplayManager
import top.broncho.mvvm.base.BaseVMActivity

class TodoActivity : BaseVMActivity<ActivityTodoBinding>() {

    private var mType = 0

    private var mTodoFragment: TodoFragment? = null

    private lateinit var datas: MutableList<TodoTypeBean>

    /**
     * PopupWindow
     */
    private var mSwitchPopupWindow: PopupWindow? = null

    override fun getLayoutId(): Int = R.layout.activity_todo

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
        initView()
    }

    fun initData() {
        datas = getTypeData()
    }

    fun initView() {
        toolbar.run {
            title = datas[0].name // getString(R.string.nav_todo)
            setSupportActionBar(this)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        }
        binding.bottomNavigation.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.action_notodo -> {
                    mTodoFragment?.onTodoChange(mType, false)
                    true
                }
                R.id.action_completed -> {
                    mTodoFragment?.onTodoChange(mType, true)
                    true
                }
                else -> {
                    false
                }
            }
        }

        binding.floatingActionBtn.clicks().onEach {
            startActivity(Intent(this, CommonActivity::class.java).apply {
                putExtra(Constant.TYPE_KEY, Constant.Type.ADD_TODO_TYPE_KEY)
                putExtra(Constant.TODO_TYPE, mType)
            })
        }.launchIn(lifecycleScope)

        val transaction = supportFragmentManager.beginTransaction()
        if (mTodoFragment == null) {
            mTodoFragment = TodoFragment.getInstance(mType)
            transaction.add(R.id.container, mTodoFragment!!, "todo")
        } else {
            transaction.show(mTodoFragment!!)
        }
        transaction.commit()
    }

    private fun getTypeData(): MutableList<TodoTypeBean> {
        val list = mutableListOf<TodoTypeBean>()
        list.add(TodoTypeBean(0, "只用这一个", true))
        list.add(TodoTypeBean(1, "工作", false))
        list.add(TodoTypeBean(2, "学习", false))
        list.add(TodoTypeBean(3, "生活", false))
        return list
    }

    /**
     * 初始化 PopupWindow
     */
    private fun initPopupWindow(dataList: List<TodoTypeBean>) {
        val recyclerView = layoutInflater.inflate(R.layout.layout_popup_todo, null) as RecyclerView
        val adapter = TodoPopupAdapter()
        adapter.setNewData(dataList)
        adapter.setOnItemClickListener { adapter, view, position ->
            mSwitchPopupWindow?.dismiss()
            val itemData = adapter.data[position] as TodoTypeBean
            mType = itemData.type
            toolbar.title = itemData.name
            adapter.data.forEachIndexed { index, any ->
                val item = any as TodoTypeBean
                item.isSelected = index == position
            }
            adapter.notifyDataSetChanged()
            bottom_navigation.selectedItemId = R.id.action_notodo
            mTodoFragment?.onTodoChange(mType, false)
        }
        recyclerView.apply {
            layoutManager =
                LinearLayoutManager(this@TodoActivity)
            this.adapter = adapter
        }
        mSwitchPopupWindow = PopupWindow(recyclerView)
        mSwitchPopupWindow?.apply {
            width = ViewGroup.LayoutParams.WRAP_CONTENT
            height = ViewGroup.LayoutParams.WRAP_CONTENT
            isOutsideTouchable = true
            elevation = DisplayManager.dip2px(10F).toFloat()
            setOnDismissListener {
                dismiss()
            }
            setTouchInterceptor { v, event ->
                if (event.action == MotionEvent.ACTION_OUTSIDE) {
                    dismiss()
                    true
                }
                false
            }
        }
    }

    /**
     * 展示 PopupWindow
     */
    private fun showPopupWindow(dataList: MutableList<TodoTypeBean>) {
        if (mSwitchPopupWindow == null) initPopupWindow(dataList)
        if (mSwitchPopupWindow?.isShowing == true) mSwitchPopupWindow?.dismiss()
        mSwitchPopupWindow?.showAsDropDown(toolbar, -DisplayManager.dip2px(5F), 0, Gravity.END)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menu?.clear()
        menuInflater.inflate(R.menu.menu_todo, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_todo_type -> {
                showPopupWindow(datas)
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
}
